# -*- coding: utf-8 -*-
import requests
import json
import csv
cookies = {
    'AlteonP10': 'A6pAFSw/F6ye2Yl2LfvlFA$$',
    'apache': 'bbfde8c184f3e1c6074ffab28a313c87',
    'ags': 'a23ede7e97bccb1b2380be21609ada80',
    '_ulta_id.ECM-Prod.ccc4': '08fe72e24da7a44b',
    '_ulta_ses.ECM-Prod.ccc4': 'c02ba244a49b5a54',
}

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0',
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
    # 'Accept-Encoding': 'gzip, deflate, br, zstd',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'X-Requested-With': 'XMLHttpRequest',
    'Origin': 'https://iftp.chinamoney.com.cn',
    'Connection': 'keep-alive',
    'Referer': 'https://iftp.chinamoney.com.cn/english/bdInfo/',
    # 'Cookie': 'AlteonP10=A6pAFSw/F6ye2Yl2LfvlFA$$; apache=bbfde8c184f3e1c6074ffab28a313c87; ags=a23ede7e97bccb1b2380be21609ada80; _ulta_id.ECM-Prod.ccc4=08fe72e24da7a44b; _ulta_ses.ECM-Prod.ccc4=c02ba244a49b5a54',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'Priority': 'u=0',
}

data = {
    'pageNo': '1',
    'pageSize': '30',
    'isin': '',
    'bondCode': '',
    'issueEnty': '',
    'bondType': '100001',
    'couponType': '',
    'issueYear': '2023',
    'rtngShrt': '',
    'bondSpclPrjctVrty': '',
}

response = requests.post(
    'https://iftp.chinamoney.com.cn/ags/ms/cm-u-bond-md/BondMarketInfoListEN',
    cookies=cookies,
    headers=headers,
    data=data,
)
in_data = [['ISIN','Bond Code','Issuer','Bond Type','Issue Date','Latest Rating']]
for page in range(1,int((int(json.loads(response.text)['data']['total'])/15))+2):
    data = {
        'pageNo': str(page),
        'pageSize': '15',
        'isin': '',
        'bondCode': '',
        'issueEnty': '',
        'bondType': '100001',
        'couponType': '',
        'issueYear': '2023',
        'rtngShrt': '',
        'bondSpclPrjctVrty': '',
    }

    response = requests.post(
        'https://iftp.chinamoney.com.cn/ags/ms/cm-u-bond-md/BondMarketInfoListEN',
        cookies=cookies,
        headers=headers,
        data=data,
    )
    for i in json.loads(response.text)['data']['resultList']:
        in_data.append([i['isin'],i['bondCode'],i['entyFullName'],i['bondType'],i['issueStartDate'],i['debtRtng']])
# 保存到 CSV 文件
with open('output.csv', mode='w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerows(in_data)

print("CSV 文件已成功保存")